<template>
  <div>
    <div class="hd">
      <span @click="$router.go(-1)"> 返回 </span>
      订单处理
    </div>
    <md-steps
      :steps="steps"
      :current="step">
    </md-steps>
    <!--选择车型-->
    <div v-show="step===0">
      <md-field>
        <md-field-item
          title="选择车型"
          arrow="arrow-right"
          align="right"
          :value="pickerValue0"
          @click.native="carlist = true">
        </md-field-item>
        <div style="padding:10px">
          <md-check-box
            v-model="ordertype"
            :options="typelist"
            style="margin:10px 0"
          >
            <div slot="content" slot-scope="{ option }" class="payment-gateway">
              <p v-text="option.text"></p>
              <p class="muted" ></p>
            </div>
          </md-check-box>
          <md-check-box
            v-model="orderinfo.need_driver"
            :options="options"
          >
            <div slot="content" slot-scope="{ option }" class="payment-gateway">
              <p v-text="option.text"></p>
              <p class="muted" ></p>
            </div>
          </md-check-box>
          <md-check-box
            v-model="orderinfo.sm"
            :options="options2"
          >
            <div slot="content" slot-scope="{ option }" class="payment-gateway">
              <p v-text="option.text"></p>
              <p class="muted" ></p>
            </div>
          </md-check-box>
        </div>
        <md-input-item
          ref="sm"
          title="上门地址"
          placeholder="请填写详细的地址"
          v-model="orderinfo.address"
          clearable
          v-show="orderinfo.sm==1"
        ></md-input-item>
        <md-field-item
          title="用车时间"
          arrow="arrow-right"
          align="right"
          :value="orderinfo.sdate|moment('YYYY-MM-DD HH:mm')"
          @click.native="sdatePicker = true">
        </md-field-item>
        <md-field-item
          title="还车时间"
          arrow="arrow-right"
          align="right"
          :value="orderinfo.edate|moment('YYYY-MM-DD HH:mm')"
          @click.native="edatePicker = true">
        </md-field-item>
      </md-field>

    </div>

    <!--步骤二  上传证件信息-->
    <div v-show="step===1">
      <md-field>
        <md-input-item
          ref="name"
          title="真实姓名"
          placeholder="租车人姓名"
          is-title-latent
          v-model="orderinfo.lxname"
          clearable
        ></md-input-item>
        <md-input-item
          ref="id"
          title="身份证号"
          placeholder="租车人身份证号"
          is-title-latent
          clearable
          v-model="orderinfo.idnum"
        ></md-input-item>
        <md-input-item
          ref="pbone"
          title="电话号码"
          placeholder="租车人电话号码"
          is-title-latent
          clearable
          v-model="orderinfo.phone"
        ></md-input-item>
      </md-field>

      <div class="stitle">证件照片</div>
      <div class="md-example-child md-example-child-reader md-example-child-reader-0">
        <ul class="image-reader-list">
          <li
            v-if="idphotoa"
            class="image-reader-item"
            :style="{
          'backgroundImage': `url(${idphotoa})`,
          'backgroundPosition': 'center center',
          'backgroundRepeat': 'no-repeat',
          'backgroundSize': 'cover'
        }">
            <md-icon
              class="image-reader-item-del"
              name="circle-cross"
              color="#666"
              @click.native="idphotoa=''">
            </md-icon>
          </li>
          <li class="image-reader-item add" v-else>
            <md-image-reader
              name="reader0"
              @select="onReaderSelect"
              @complete="uploadIdA"
              @error="onReaderError"
            ></md-image-reader>
            <md-icon name="hollow-plus" size="md" color="#CCC"></md-icon>
            <p>身份证正面</p>
          </li>
          <li
            v-if="idphotob"
            class="image-reader-item"
            :style="{
          'backgroundImage': `url(${idphotob})`,
          'backgroundPosition': 'center center',
          'backgroundRepeat': 'no-repeat',
          'backgroundSize': 'cover'
        }">
            <md-icon
              class="image-reader-item-del"
              name="circle-cross"
              color="#666"
              @click.native="idphotob=''">
            </md-icon>
          </li>
          <li class="image-reader-item add" v-else>
            <md-image-reader
              name="reader0"
              @select="onReaderSelect"
              @complete="uploadIdB"
              @error="onReaderError"
            ></md-image-reader>
            <md-icon name="hollow-plus" size="md" color="#CCC"></md-icon>
            <p>身份证反面</p>
          </li>

          <li
            v-if="license_a"
            class="image-reader-item"
            :style="{
          'backgroundImage': `url(${license_a})`,
          'backgroundPosition': 'center center',
          'backgroundRepeat': 'no-repeat',
          'backgroundSize': 'cover'
        }">
            <md-icon
              class="image-reader-item-del"
              name="circle-cross"
              color="#666"
              @click.native="license_a=''">
            </md-icon>
          </li>
          <li class="image-reader-item add" v-else>
            <md-image-reader
              name="reader0"
              @select="onReaderSelect"
              @complete="uploadLicA"
              @error="onReaderError"
            ></md-image-reader>
            <md-icon name="hollow-plus" size="md" color="#CCC"></md-icon>
            <p>驾驶证正面</p>
          </li>
          <li
            v-if="license_b"
            class="image-reader-item"
            :style="{
          'backgroundImage': `url(${license_b})`,
          'backgroundPosition': 'center center',
          'backgroundRepeat': 'no-repeat',
          'backgroundSize': 'cover'
        }">
            <md-icon
              class="image-reader-item-del"
              name="circle-cross"
              color="#666"
              @click.native="license_b=''">
            </md-icon>
          </li>
          <li class="image-reader-item add" v-else>
            <md-image-reader
              name="reader0"
              @select="onReaderSelect"
              @complete="uploadLicB"
              @error="onReaderError"
            ></md-image-reader>
            <md-icon name="hollow-plus" size="md" color="#CCC"></md-icon>
            <p>驾驶证反面</p>
          </li>
        </ul>
        <div style="clear:both"></div>
      </div>
    </div>
    <!--步骤三  确认订单-->
    <div class="order" v-show="step===2">
      <div>
    <!--    <div class="orderpic" :style="{ overflow: 'hidden', background: 'url('+JSON.parse(carinfo.imgs)[0].url+') center center' , backgroundSize: 'cover'}" >
          <div class="backbtn" @click="$router.go(-1)">返回</div>
        </div>-->
        <div class="carname">
          车
        </div>

        <!--基本参数-->
        <div class="infotitle">费用明细</div>
        <div class="feedetail">
          <div class="lineAll clearfix">
            <span class="fl">总计</span>
            <span class="fr tot" >{{total_fee}}元</span>
          </div>
          <div class="lineItem clearfix" >
            <div class="fl" >租车费用<!--<span>{{200}}/4小时</span>--></div>
            <div class="fr">
              {{orderinfo.fee}}元
              <!--<span> {{'说明'}} </span>-->
            </div>
          </div>

          <div class="lineItem clearfix" v-if="orderinfo.need_driver==1">
            <div class="fl" >司机代驾</div>
            <div class="fr">
              {{orderinfo.driver_fee}}元
              <span>  </span>
            </div>
          </div>
          <!--      <div class="lineItem clearfix" >
                  <div class="fl">服务费<span></span></div>
                  <div class="fr">{{service_fee}}元<span></span></div>
                </div>-->

          <!--        <div class="lineItem clearfix">
                    <div class="fl">保险费用
                      <span> {{$store.state.feetander.insurance_fee}}/天 </span>
                    </div>
                    <div class="fr">{{insurance_fee}}元
                      <span>{{countDatestr}}</span>
                    </div>
                  </div>-->

          <div class="lineItem clearfix"  v-if="orderinfo.sm">
            <div class="fl">上门服务费
              <span> {{50}}/市区范围</span>
            </div>
            <div class="fr">{{50}}元
              <span></span>
            </div>
          </div>

          <div class="lineItem clearfix" >
            <div class="fl">保证金<span></span>
            </div>
            <div class="fr">{{orderinfo.carinfo.despoil}}元<span>取车时支付</span></div>
          </div>

        </div>

        <!--订单联系方式-->
        <div class="infotitle">订车人联系方式</div>
        <div style="padding: 0 40px 20px">
          <md-field>
            <md-input-item
              ref="orderpeople"
              title="联系人"
              v-model="orderinfo.lxname"
              placeholder="请填写您的姓名"
              readonly
              :maxlength="10"
            ></md-input-item>
            <md-input-item
              title="手机号"
              type="phone"
              v-model="orderinfo.phone"
              placeholder="填写您的11位手机号码"
              readonly
            ></md-input-item>

          </md-field>
        </div>

        <div class="infotitle" v-if="orderinfo.address">取车地址</div>
        <div style="padding: 0 40px 20px;color:#666;text-align: center;line-height: 2;">
          <div style="font-size: 14px;"> {{orderinfo.address}}</div>
        </div>

        <!--订单用车时间-->
        <div class="infotitle">用车时间</div>
        <div style="padding: 0 40px 20px;color:#666;text-align: center;line-height: 2;">
          <div style="font-size: 14px;"> <span style="color:#333">取车时间</span> {{$store.state.order.sdate|moment('YYYY-MM-DD hh:mm')}} </div>
          <div style="font-size: 14px;"> <span style="color:#333">还车时间</span> {{$store.state.order.edate|moment('YYYY-MM-DD hh:mm')}}  </div>
        </div>

      </div>

    </div>

    <div class="stepzone">
      <md-button @click="prestep" v-show="step!=0">上一步</md-button>
      <md-button @click="nextstep" v-show="step!=2">下一步</md-button>
      <md-button @click="topay" v-show="step==2">确认订单</md-button>
    </div>

    <!--各种弹出层-->

    <div class="carlist" v-show="carlist">
      <Carlist @click="getcarinfo"></Carlist>
    </div>
    <md-date-picker
      ref="sdatePicker"
      type="datetime"
      v-model="sdatePicker"
      :default-date="currentDate"
      @confirm="sdateHandle"
    ></md-date-picker>
    <md-date-picker
      ref="edatePicker"
      type="datetime"
      :default-date="currentDate1"
      v-model="edatePicker"
      :minDate="orderinfo.sdate ? orderinfo.sdate  : new Date()"
      @confirm="edateHandle"
    ></md-date-picker>
  </div>
</template>

<script>
import {Toast} from 'mand-mobile'
import Carlist from '@/components/carlist.vue'
import imageProcessor from 'mand-mobile/components/image-reader/image-processor'
export default {
  name: 'add',
  components: {
    Carlist
  },
  data () {
    return {
      edatePicker: false,
      sdatePicker: false,
      currentDate: new Date(),
      currentDate1: new Date(),
      carlist: false,
      idphotoa: '',
      idphotob: '',
      license_a: '',
      license_b: '',
      ordertype: '3',
      step: 0,
      pickerCar: false,
      pickerValue0: '',
      sm: 0,
      typelist: [{text: '4小时', value: '1'}, {text: '8小时', value: '2'}, {text: '按天计费', value: '3'}],
      options: [{text: '需要司机', value: '1'}, {text: '自驾', value: '0'}],
      options2: [{text: '送车上门', value: 1}, {text: '到店取车', value: 0}],
      pickerData0: [
        {text: '2015', value: 1}

      ],
      steps: [ {name: '车辆信息'}, {name: '个人信息'}, {name: '确认订单'} ],
      orderinfo: {
        cid: '',
        carinfo: {},
        sdate: '',
        edate: '',
        need_driver: '1',
        lxname: '',
        idnum: '',
        phone: '',
        fee: 0.00,
        sm: 0,
        address: '',
        driver_fee: 0.00
      }
    }
  },
  watch: {
    ordertype: function (nv) {
      let _time = this.orderinfo.sdate.getTime()
      let _d = new Date(_time)

      if (nv === '3') {
        _d.setDate(_d.getDate() + 1)
      }
      if (nv === '2') {
        _d.setHours(_d.getHours() + 8)
      }
      if (nv === '1') {
        _d.setHours(_d.getHours() + 4)
      }
      console.log(_d)
      this.orderinfo.edate = _d
    }
  },
  computed: {
    total_fee: function () {
      let _fee = this.orderinfo.fee
      if (this.orderinfo.need_driver == 1) {
        _fee += this.orderinfo.driver_fee
      }
      if (this.orderinfo.sm == 1) {
        _fee += 50
      }
      return _fee
    }
  },
  created: async function () {
    let _d1 = new Date()
    let _d2 = new Date()
    this.orderinfo.sdate = _d1
    _d2.setDate(_d2.getDate() + 2)
    this.orderinfo.edate = _d2
  },
  beforeMount: async function () {

  },
  mounted: async function () {
  },
  methods: {
    async nextstep () {
      // 进入订单确认前 需要对订单内容进行过滤
      if (this.step === 1) {
        const zhreg = /^[\u4e00-\u9fa5]+$/ // 姓名中文
        const telreg = /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/ // 手机号码正则
        if (!zhreg.test(this.orderinfo.lxname)) {
          Toast.info('请填写正确的姓名'); return false
        }
        if (!telreg.test(this.orderinfo.phone)) {
          Toast.info('请填写正确的手机号码'); return false
        }
        if (this.orderinfo.sm && !this.orderinfo.address) {
          Toast.info('送车上门请填写正确的地址'); return false
        }

        // 证件信息不能为空 包括图片
        if (!this.orderinfo.idnum) {
          Toast.info('请上传正确的身份证号码'); return false
        }
        if (!this.idphotoa) {
          Toast.info('请上传正确的身份证正面图片'); return false
        }
        if (!this.idphotob) {
          Toast.info('请上传正确的身份证反面图片'); return false
        }
        if (!this.license_a) {
          Toast.info('请上传正确的驾驶证正面图片'); return false
        }
        if (!this.license_b) {
          Toast.info('请上传正确的驾驶证反面图片'); return false
        }

        // 获取车的收费标准
        let _res = await this.$api.post('/fx/feestander', {cid: this.orderinfo.cid})
        let _fee = {}
        if (_res.data.state) {
          _fee = _res.data.data
          // 执行费用计算
          await this.countFee(_fee)
        } else {
          Toast.info('系统错误请重新再试'); return false
        }
      }

      this.step++
    },
    prestep () {
      if (this.step == 0) {
        return false
      }
      this.step--
    },
    countFee (_fee) {
      const _amount = 0
      if (this.ordertype == 1) {
        this.orderinfo.fee = _fee.fourfee.fee
        this.orderinfo.driver_fee = _fee.fourfee.driver_fee
      } else if (this.ordertype == 2) {
        this.orderinfo.fee = _fee.eightfee.fee
        this.orderinfo.driver_fee = _fee.eightfee.driver_fee
      } else if (this.ordertype == 3) {
        // 计算租用多久
        let _d = (this.orderinfo.edate - this.orderinfo.sdate) / (24 * 60 * 60 * 1000)
        _d = Math.ceil(_d)

        this.orderinfo.fee = _fee.dayfee.fee * _d
        this.orderinfo.driver_fee = _fee.dayfee.driver_fee * _d
      }
    },
    getcarinfo (r) {
      console.log(r)
      this.orderinfo.cid = r.cid
      this.orderinfo.carinfo = r.car
      this.carlist = false
      this.pickerValue0 = r.car.name
    },
    onReaderSelect (name, {files}) {
      Toast.loading('图片读取中...')
    },
    async uploadIdA (name, {dataUrl, file}) {
      await this._uploadFile(file, 'ida')
    },
    async uploadIdB (name, {dataUrl, file}) {
      await this._uploadFile(file, 'idb')
    },
    async uploadLicA (name, {dataUrl, file}) {
      await this._uploadFile(file, 'lica')
    },
    async uploadLicB (name, {dataUrl, file}) {
      await this._uploadFile(file, 'licb')
    },
    async _uploadFile (file, target) {
      // 执行上传
      let formData = new FormData()

      formData.append('file', file)
      if (file) {
        Toast.loading('上传中请等待')
        let res = await this.$api.post('/fx/uploadimg', formData, {
          headers: {'Content-Type': 'multipart/form-data'}
        })
        const preimgurl = 'http://tmc.guotaijinxing.com/public/avt/'
        if (res.data.fileName) {
          if (target === 'ida') {
            this.idphotoa = preimgurl + res.data.fileName
            this.orderinfo.idphotoa = preimgurl + res.data.fileName
          }
          if (target === 'idb') {
            this.idphotob = preimgurl + res.data.fileName
            this.orderinfo.idphotob = preimgurl + res.data.fileName
          }
          if (target === 'lica') {
            this.license_a = preimgurl + res.data.fileName
            this.orderinfo.license_a = preimgurl + res.data.fileName
          }
          if (target === 'licb') {
            this.license_b = preimgurl + res.data.fileName
            this.orderinfo.license_b = preimgurl + res.data.fileName
          }
          Toast.succeed('上传成功')
        } else {
          Toast.failed('上传失败请重新上传')
        }
      }
    },
    async onReaderComplete (name, {dataUrl, file}) {
      const demoImageList = this.imageList[name] || []

      // 执行上传
      let formData = new FormData()

      formData.append('file', file)
      if (file) {
        Toast.loading('上传中请等待')
        let res = await this.$api.post('/fx/uploadimg', formData, {
          headers: {'Content-Type': 'multipart/form-data'}
        })
        if (res.data.fileName) {
          demoImageList.push('http://tmc.guotaijinxing.com/public/avt/' + res.data.fileName)
          Toast.succeed('上传成功')
        } else {
          Toast.failed('上传失败请重新上传')
        }
      }

      this.$set(this.imageList, name, demoImageList)
    },
    onReaderError (name, {msg}) {
      Toast.failed(msg)
    },
    onDeleteImage (name, index) {
      const demoImageList = this.imageList[name] || []
      demoImageList.splice(index, 1)
      this.$set(this.imageList, name, demoImageList)
    },
    async  sdateHandle (r) {
      let _date = new Date()
      _date.setFullYear(r[0].value)
      _date.setMonth(r[1].value - 1)
      _date.setDate(r[2].value)
      _date.setHours(r[3].value)
      _date.setMinutes(r[4].value)
      this.orderinfo.sdate = _date
    },
    async  edateHandle (r) {
      let _date = new Date()
      _date.setFullYear(r[0].value)
      _date.setMonth(r[1].value - 1)
      _date.setDate(r[2].value)
      _date.setHours(r[3].value)
      _date.setMinutes(r[4].value)
      this.orderinfo.edate = _date
    },
    optionRender (item) {
      return `<div class="md-radio-custom-title">${item.text}</div><div class="md-radio-custom-brief"></div>`
    },
    async topay () {
      console.log(this.orderinfo)
      let _postData = {
        s_date: this.orderinfo.sdate.getTime(),
        e_date: this.orderinfo.edate.getTime(),
        cid: this.orderinfo.cid,
        phone: this.orderinfo.phone,
        lxname: this.orderinfo.lxname,
        need_driver: this.orderinfo.need_driver,
        driver_fee: this.orderinfo.need_driver == 1 ? this.orderinfo.driver_fee : 0,
        fee: this.total_fee,
        rid: this.$store.state.agent.openid ? this.$store.state.agent.openid : 1,
        car_fee: this.orderinfo.fee,
        address: this.orderinfo.sm == 1 ? this.orderinfo.address : '',
        despoil_fee: this.orderinfo.carinfo.despoil,
        send_fee: this.orderinfo.sm == 1 ? 50 : '',
        type: this.ordertype,
        license_a: this.license_a,
        license_b: this.license_a,
        idphotoa: this.idphotoa,
        idphotob: this.idphotob,
        idnum: this.orderinfo.idnum

      }

      let res = await this.$api.post('/fx/addOrder', _postData)
      if (res.data.state) {
        Toast.succeed('添加成功')
      } else {
        Toast.failed('添加失败')
      }
    }
  }
}
</script>

<style lang="stylus" scoped>
  font-minor-normal = 12px
  .stepzone
    display:flex
    margin-top:20px
    div{
      width: 45vw;
    }
  .stitle
    font-size:14px
    line-height:2
    padding:10px
  .carlist
    position: fixed
    width: 100%
    height: 100%
    top:0
    left:0
    background: #fff
    z-index: 99999

  .md-example-child-reader
    padding:10px
    .image-reader-list
      float left
      width 100%
      .image-reader-item
        position relative
        float left
        width 23.5%
        padding-bottom 23.5%
        margin-bottom 2%
        margin-right 2%
        background color-bg-base
        box-sizing border-box
        list-style none
        border-radius radius-normal
        hairline(all, color-border-base)
        background-size cover
        &:nth-of-type(4n)
          margin-right 0
        &.add
          .md-icon
            position absolute
            top 40%
            left 50%
            transform translate(-50%, -50%)
            opacity .5
          p
            position absolute
            top 50%
            left 0
            width 100%
            margin-top 15px
            font-size font-minor-normal
            color color-text-disabled
            text-align center
        .image-reader-item-del
          position absolute
          top 5px
          right 5px
          z-index 3
          background #EEE
          border-radius radius-circle

</style>

<style scoped>
  .feedetail{
    /*background: rgb(244,243,248);*/
    padding:20px 40px;
    font-size: 14px;

  }

  .order{
    display: flex;
    flex-direction: column;
  }
  .orderpic{
    height: 150px;
    position: relative;
  }
  .backbtn{
    width: 50px;
    height: 30px;
    text-align: center;
    line-height: 30px;
    position: absolute;
    top:25px;
    left:20px;
    font-size: 12px;
    background: rgba(0,0,0,.7);
    color:#fff
  }
  .carname{
    text-align: center;
    line-height: 40px;
  }
  .carLogo{
    text-align: center;
  }
  .carLogo >i {
    font-size: 20px;
    color:#666;
    line-height: 30px;
  }
  .info{
    margin-top: 15px;
    padding:0 20px
  }
  .infotitle{
    text-align: center;
    font-size: 12px;
    line-height: 2;
  }
  .infotitle:after{
    content: "";
    margin:0 auto;
    width: 30px;
    border-bottom:2px solid #ccc;
    display: block;
  }
  .arg{
    display: flex;
    height: 80px;
    margin-top: 15px;
  }
  .arg > div{
    width: 0;
    flex-grow: 1;
    text-align: center;
  }

  .argtitle{
    font-size: 12px;
    display: block;
    line-height: 2;
  }
  .arginfo{
    display: block;
    font-size: 18px;
  }
  .pricebox{
    padding:0 40px;
    margin:10px 0;
  }
  .priceitem{
    margin-bottom: 20px;
  }

  .l2{
    text-align: right;
    font-size: 12px;
    color:#999;
    text-decoration-line:line-through;

  }
  .l3{

    text-align: right;
    font-size: 12px;
    color:#666
  }

  .carinfo{
    padding:10px 40px;
    text-indent: 2em;
    font-size:12px;
    color:#666;
  }
  .checkout{
    height: 50px;
    background: -webkit-linear-gradient(top left,#6a78d0,#7986db);
    color:#fff;
    line-height: 50px;
    text-align: center;

  }
  .custom{
    text-align: center;
    line-height: 40px;
  }
  .lineAll > span:first-of-type{
    font-size: 16px;
  }
  .tot{
    font-size: 16px;
    color:#6a78d0;
    font-weight: 500;
  }
  .feedetail .lineItem{
    color:rgb(162,162,162);
    margin: 5px 0;
  }

  .lineItem span{
    font-size: 12px;
    display: block;
    transform: scale(.9);

  }
  .lineItem > .fr{
    text-align: right;
  }
  .lineItem > .fr  span{
    text-align: right;
  }

</style>
